import subprocess

import dofile


def verify(input_path, output_path, class_id, user_id):
    a = 0
    i = 0
    answer = dofile.get_output(output_path)
    input_data = dofile.get_input(input_path)
    print(answer)
    print(input_data)
    
    # 如果没有输入数据但有输出数据，说明是不需要输入的程序（如Hello World）
    if len(input_data) == 0 and len(answer) > 0:
        # 对于不需要输入的程序，使用空字符串作为输入
        result = cfile_to_exefile("", answer[0], class_id, user_id)
        if result[0] == -1:
            return result
        if result[0] == 1:
            return [100, ]  # 输出正确，给满分
        else:
            return [0, ]    # 输出错误，给0分
    
    # 正常的测试用例处理
    for data_str in input_data:
        if i >= len(answer):
            return [-1, "输出用例数量不足"]
        answer_str = answer[i]
        result = cfile_to_exefile(data_str, answer_str, class_id, user_id)
        if result[0] == -1:
            return result
        if result[0] == 1:
            a += 1
        i += 1
    
    if i == 0:
        return [-1, "没有有效的测试用例"]
    return [a * 100 / i, ]


def cfile_to_exefile(datas, answer, class_id, user_id):
    import os
    # Windows系统使用.exe，Linux使用.out
    if os.name == 'nt':  # Windows
        filename = str(user_id) + ".exe"
        # Windows下使用完整路径
        path = os.path.abspath("code/class" + str(class_id))
        full_path = os.path.join(path, filename)
    else:  # Linux/Unix
        filename = "./" + str(user_id) + ".out"
        path = "code/class" + str(class_id)
        full_path = filename
    
    print(f"执行文件: {filename}")
    print(f"工作目录: {path}")
    print(f"完整路径: {full_path}")
    
    datas = datas
    print(f"输入数据: '{datas}'")
    try:
        if os.name == 'nt':
            proc = subprocess.run([full_path], stdout=subprocess.PIPE, input=datas, text=True, timeout=5)
        else:
            proc = subprocess.run(filename, cwd=path, stdout=subprocess.PIPE, input=datas, text=True, timeout=5)
        its_answer = proc.stdout
        # itscd1_answer = str(its_answer)
        # its_answer = its_answer.replace(r"\r", "")
        print(its_answer)
        print("作业答案")
        print(answer)
        if its_answer.strip() == answer:
            print("对+1")
            return [1, ]
        else:
            print("错+1")
            return [0, ]
    except subprocess.TimeoutExpired:
        return [-1, "Command execution timed out"]
    except Exception as e:
        # 处理其他异常
        return [-1, str(e)]
